<?php
/**
 * ECalendarViewDataProvider.php
 *
 * @author Martin Ludvik <matolud@gmail.com>
 * @copyright Copyright &copy; 2013 by Martin Ludvik
 * @license http://opensource.org/licenses/MIT MIT license
 */

Yii::import('ecalendarview.ECalendarViewItem');
Yii::import('ecalendarview.ECalendarViewPagination');

/**
 * The data provider prepares data to be shown by {@link ECalendarView}.
 */
class ECalendarViewDataProvider extends CComponent {

  /**
   * @var ECalendarViewPagination The pagination.
   */
  private $_pagination;

  /**
   * Constructs the data provider and sets it's attributes to default values.
   * @param array $config The attributes as key=>value map.
   */
  public function __construct(array $config = array()) {
    $this->_pagination = new ECalendarViewPagination();

    foreach($config as $key => $value) {
      $this->$key = $value;
    }
  }

  /**
   * Sets the pagination's attributes.
   * @param array $config The attributes as key=>value map.
   */
  public function setPagination(array $config) {
    foreach($config as $key => $value) {
      $this->getPagination()->$key = $value;
    }
  }

  /**
   * @see ECalendarViewDataProvider::$_pagination
   */
  public function getPagination() {
    return $this->_pagination;
  }

  /**
   * Retrieves the data.
   * @return array The array of {@link ECalendarViewItem}s.
   */
  public function getData() {
    $data = array();
    $startDate = $this->getPagination()->getFirstPageDate();
    $endDate = $this->getPagination()->getLastPageDate();
    $dateIterator = clone($startDate);
	
	//carga las citas que esten presentes en el intervalo a desplegar en calendario
	$citasEnIntervalo = Cita::model()->getCitasIntervalo($startDate->format('Y-m-d'), $endDate->format('Y-m-d'));
	
    while($dateIterator <= $endDate) {
	
	  //carga la fecha actual en formato yyyy-mm-dd, correspondiendo a formato de BD
	  $currentDate = $dateIterator->format('Y-m-d');
	  
	  //variable que guarda boolean si hay citas o no
	  $citasAvailable = true;
	  //cuenta las citas por fecha. deberian ser maximo 20
	  $citasCounter=0;
	  
	  for ($i=0; $i < sizeof($citasEnIntervalo); $i++){
		if ($citasEnIntervalo[$i]->fecha == $currentDate)
			$citasCounter++;
	  }
	  
	  //si hay 20 o mas citas, no hay mas citas disponibles
	  if($citasCounter >= 20)
		$citasAvailable = false;
	
      $data[] = new ECalendarViewItem(array(
          'date' => clone($dateIterator),
          'isCurrentDate' => $this->getPagination()->isCurrentDate($dateIterator),
          'isRelevantDate' => $this->getPagination()->isRelevantDate($dateIterator),
		  'citasAvailable' => $citasAvailable, //se envia el valor de $citasAvailable a el ECalendarViewItem
        ));
		
      $dateIterator->add(new DateInterval('P1D'));
    }
	
    return $data;
  }

}
